//
//  MGTableView.m
//  Mango
//
//  Created by 胡超 on 2017/11/29.
//  Copyright © 2017年 胡超., ltd. All rights reserved.
//

#import "MGTableView.h"
#import "MGTableViewSection.h"

@interface MGTableView ()
@end

@implementation MGTableView

#pragma mark - Override

- (void)dealloc {
    
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if (self = [super initWithFrame:frame style:style]) {
        _option = [[MGTableViewOption alloc] init];
        _sections = [NSArray array];
        self.delegate = self;
        self.dataSource = self;
        
        if (@available(iOS 15.0, *)) {
            self.sectionHeaderTopPadding = 0;
        }
    }
    return self;
}

- (UINavigationController *)navigationController {
    for (UIView *nextView = self; nextView; nextView = self.superview) {
        UIResponder *nextResponder = nextView.nextResponder;
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return ((UIViewController *)nextResponder).navigationController;
        }
    }
    return nil;
}

#pragma mark - Add Section

- (void)addSection:(void(^)(MGTableViewSection *section))sectionConfiguration {
    MGTableViewSection *section = [[MGTableViewSection alloc] init];
    section.tableView = self;
    section.option = self.option;
    sectionConfiguration(section);
    _sections = [_sections arrayByAddingObject:section];
}

- (void)insertSectionAtIndex:(NSUInteger)sectionIndex sectionConfiguration:(void(^)(MGTableViewSection *section))sectionConfiguration {
    MGTableViewSection *section = [[MGTableViewSection alloc] init];
    section.tableView = self;
    section.option = self.option;
    sectionConfiguration(section);
    
    NSMutableArray *mutableSections = [_sections mutableCopy];
    [mutableSections insertObject:section atIndex:sectionIndex];
    _sections = [NSArray arrayWithArray:mutableSections];
}

#pragma mark - Update Cell

- (void)updateCellImage:(UIImage *)image forIndexPath:(NSIndexPath *)indexPath {
    self.sections[indexPath.section].cells[indexPath.row].imageView.image = image;
}

- (void)updateCellTitle:(NSString *)title forIndexPath:(NSIndexPath *)indexPath {
    self.sections[indexPath.section].cells[indexPath.row].textLabel.text = title;
}

- (void)updateCellDetail:(NSString *)detail forIndexPath:(NSIndexPath *)indexPath {
    self.sections[indexPath.section].cells[indexPath.row].detailTextLabel.text = detail;
}

- (void)updateCellSwitchOn:(BOOL)on animated:(BOOL)animated forIndexPath:(NSIndexPath *)indexPath {
    UIView *accessoryView = self.sections[indexPath.section].cells[indexPath.row].accessoryView;
    if ([accessoryView isKindOfClass:UISwitch.class]) {
        UISwitch *swc = (UISwitch *)accessoryView;
        [swc setOn:on animated:animated];
    }
}

- (void)updateCellSwitchEnable:(BOOL)enable forIndexPath:(NSIndexPath *)indexPath {
    UIView *accessoryView = self.sections[indexPath.section].cells[indexPath.row].accessoryView;
    if ([accessoryView isKindOfClass:UISwitch.class]) {
        UISwitch *swc = (UISwitch *)accessoryView;
        [swc setEnabled:enable];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sections[section].cells.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.sections[indexPath.section].cells[indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = self.sections[indexPath.section].cells[indexPath.row].cellHeight;
    if (height < 0) {
        return self.option.cellHeight;
    } else {
        return height;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.sections[section].headerTitle;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return self.sections[section].footerTitle;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    MGTableViewCell *cell = self.sections[indexPath.section].cells[indexPath.row];
    if ([cell.onSelectActionTarget respondsToSelector:cell.onSelectActionSelector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [cell.onSelectActionTarget performSelector:cell.onSelectActionSelector withObject:cell withObject:indexPath];
#pragma clang diagnostic pop
    } else if (cell.onSelectActionPushClass) {
        UIViewController *viewController = [[cell.onSelectActionPushClass alloc] init];
        [viewController setTitle:cell.textLabel.text];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectionIdx {
    MGTableViewSection *section = self.sections[sectionIdx];
    if (section.heightForHeader >= 0) {
        return MAX(section.heightForHeader, 0.000);
    } else {
        if (section.headerTitle) {
            return 44.0;
        } else {
            return MAX(self.option.sectionHeaderHeight, 0.000);
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)sectionIdx {
    MGTableViewSection *section = self.sections[sectionIdx];
    if (section.heightForFooter >= 0) {
        return MAX(section.heightForFooter, 0.000);
    } else {
        if (section.footerTitle) {
            return 44.0;
        } else {
            return MAX(self.option.sectionFooterHeight, 0.000);
        }
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = self.sections[section].headerView;
    if (!headerView && self.option.sectionHeaderBackgroundColor) {
        static NSString *identifier = @"QKTableSectionHeaderView";
        headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
        if (!headerView) {
            UITableViewHeaderFooterView *reuseHeaderView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:identifier];
            reuseHeaderView.contentView.backgroundColor = self.option.sectionHeaderBackgroundColor;
            headerView = reuseHeaderView;
        }
    }
    return headerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = self.sections[section].footerView;
    if (!footerView && self.option.sectionFooterBackgroundColor) {
        static NSString *identifier = @"QKTableSectionFooterView";
        footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
        if (!footerView) {
            UITableViewHeaderFooterView *reuseFooterView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:identifier];
            reuseFooterView.contentView.backgroundColor = self.option.sectionFooterBackgroundColor;
            footerView = reuseFooterView;
        }
    }
    return footerView;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([self.scrollViewDelegate respondsToSelector:@selector(scrollViewDidScroll:)]) {
        [self.scrollViewDelegate scrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self endEditing:YES];
}

@end
